<template>
    <view class="container">
        <custom-nav-bar title="我的收藏" :showBack="true" />
        <view class="content">
            <!-- 顶部选项卡 -->
            <view class="tabs">
                <view class="tab-item" :class="{ active: currentTab === 'camps' }" @tap="currentTab = 'camps'">
                    <text>营地收藏</text>
                </view>
                <view class="tab-item" :class="{ active: currentTab === 'guides' }" @tap="currentTab = 'guides'">
                    <text>攻略收藏</text>
                </view>
            </view>

            <!-- 营地收藏列表 -->
            <scroll-view class="content-section" scroll-y v-if="currentTab === 'camps'">
                <view class="camp-list" v-if="favoriteCamps.length > 0">
                    <view class="camp-item" v-for="camp in favoriteCamps" :key="camp.id">
                        <view class="delete-btn" @tap.stop="onDeleteFavorite(camp.id, 'camp')">×</view>
                        <view class="camp-content" @tap="onCampTap(camp)">
                            <image :src="camp.imageUrl" mode="aspectFill" class="camp-image" />
                            <view class="camp-info">
                                <text class="camp-name">{{ camp.name }}</text>
                                <view class="camp-meta">
                                    <text class="camp-location">{{ camp.address || '暂无地址' }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="empty-state" v-else>
                    <text>暂无收藏的营地</text>
                </view>
            </scroll-view>

            <!-- 攻略收藏列表 -->
            <scroll-view class="content-section" scroll-y v-if="currentTab === 'guides'">
                <view class="guide-list" v-if="favoriteGuides.length > 0">
                    <view class="guide-item" v-for="guide in favoriteGuides" :key="guide.id">
                        <view class="delete-btn" @tap.stop="onDeleteFavorite(guide.id, 'guide')">×</view>
                        <view class="guide-content" @tap="onGuideTap(guide)">
                            <image :src="guide.coverUrl" mode="aspectFill" class="guide-image" />
                            <view class="guide-info">
                                <text class="guide-title">{{ guide.title }}</text>
                                <text class="guide-desc">{{ guide.description }}</text>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="empty-state" v-else>
                    <text>暂无收藏的攻略</text>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { favoriteApi, campApi, guideApi } from '@/api/index'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'

const currentTab = ref('camps')

// 数据列表
const favorites = ref([])
const campList = ref([])
const guideList = ref([])

// 获取收藏列表
const fetchFavorites = async () => {
    try {
        const userInfo = uni.getStorageSync('userInfo')
        if (!userInfo || !userInfo.id) {
            throw new Error('用户未登录')
        }

        const res = await favoriteApi.getFavorites(userInfo.id)
        if (Array.isArray(res.data)) {
            favorites.value = res.data
            // 获取收藏的具体内容
            await Promise.all([fetchCamps(), fetchGuides()])
        }
    } catch (error) {
        console.error('获取收藏失败:', error)
        uni.showToast({
            title: '获取收藏失败',
            icon: 'none'
        })
    }
}

// 获取营地列表
const fetchCamps = async () => {
    try {
        // 从收藏列表中筛选出营地类型的收藏
        const campFavorites = favorites.value.filter(item => item.type === 'camp')

        // 获取完整的营地列表
        const res = await campApi.getCampList()
        if (res.data && Array.isArray(res.data)) {
            // 根据targetId匹配收藏的营地
            const favoritesCampList = res.data.filter(camp =>
                campFavorites.some(favorite => favorite.targetId === camp.id)
            ).map(camp => {
                // 找到对应的收藏记录
                const favorite = campFavorites.find(f => f.targetId === camp.id)
                // 合并营地信息和收藏信息
                return {
                    ...camp,
                    favoriteId: favorite.id,
                    targetId: favorite.targetId
                }
            })
            // 更新营地列表
            console.log('获取到的营地列表:', favoritesCampList)
            campList.value = favoritesCampList
        }
    } catch (error) {
        console.error('获取营地列表失败:', error)
        uni.showToast({
            title: '获取营地数据失败',
            icon: 'none'
        })
    }
}

// 获取攻略列表
const fetchGuides = async () => {
    try {
        // 从收藏列表中筛选出攻略类型的收藏
        const guideFavorites = favorites.value.filter(item => item.type === 'guide')

        // 获取完整的攻略列表
        const res = await guideApi.getGuideList()
        if (res.data && Array.isArray(res.data)) {
            // 根据targetId匹配收藏的攻略
            const favoritesGuideList = res.data.filter(guide =>
                guideFavorites.some(favorite => favorite.targetId === guide.id)
            ).map(guide => {
                // 找到对应的收藏记录
                const favorite = guideFavorites.find(f => f.targetId === guide.id)
                // 合并攻略信息和收藏信息
                return {
                    ...guide,
                    favoriteId: favorite.id,
                    targetId: favorite.targetId
                }
            })
            // 更新攻略列表
            console.log('获取到的攻略列表:', favoritesGuideList)
            guideList.value = favoritesGuideList
        }
    } catch (error) {
        console.error('获取攻略列表失败:', error)
        uni.showToast({
            title: '获取攻略数据失败',
            icon: 'none'
        })
    }
}

// 删除收藏
const onDeleteFavorite = async (targetid, type) => {
    const userInfo = uni.getStorageSync('userInfo')
    try {
        await favoriteApi.deleteFavorite(userInfo.id, targetid, type)
        uni.showToast({
            title: '取消收藏成功',
            icon: 'success'
        })
        // 重新加载数据
        fetchFavorites()
    } catch (error) {
        uni.showToast({
            title: '操作失败',
            icon: 'none'
        })
    }
}

// 计算属性：收藏的营地列表
const favoriteCamps = computed(() => {
    return campList.value.map(camp => ({
        id: camp.id,
        name: camp.name,
        imageUrl: camp.imageUrl,
        score: camp.score,
        distance: camp.distance,
        price: camp.price
    }))
})

// 计算属性：收藏的攻略列表
const favoriteGuides = computed(() => {
    return guideList.value.map(guide => ({
        id: guide.id,
        coverUrl: guide.coverUrl,     // 修正字段名：coverUrl 而不是 icoverUrl
        views: guide.views,
        title: guide.title,
        description: guide.description,
        createdAt: guide.createdAt,
        content: guide.content,
        categoryId: guide.categoryId // 添加分类ID用于获取相关营地
    }))
})

// 营地点击事件
const onCampTap = (camp) => {
    // 将营地数据转换为URL参数
    const params = {
        id: camp.id,
        name: camp.name,
        imageUrl: camp.imageUrl,
        score: camp.score,
        distance: camp.distance,
        price: camp.price
    }
    const query = Object.keys(params)
        .map(key => `${key}=${encodeURIComponent(params[key])}`)
        .join('&')

    uni.navigateTo({
        url: `/pages/camp-detail/index?${query}`
    })
}

// 攻略点击事件
const onGuideTap = (guide) => {
    const params = {
        id: guide.id,
        coverUrl: guide.coverUrl,     // 修正字段名：coverUrl 而不是 icoverUrl
        views: guide.views,
        title: guide.title,
        description: guide.description,
        createdAt: guide.createdAt,
        content: guide.content,
        categoryId: guide.categoryId // 添加分类ID用于获取相关营地
    }
    // 构建查询字符串
    const queryItems = []
    for (const [key, value] of Object.entries(params)) {
        if (value !== null && value !== undefined && value !== '') {
            queryItems.push(`${key}=${encodeURIComponent(value)}`)
        }
    }
    const query = queryItems.join('&')

    uni.navigateTo({
        url: `/pages/guide-detail/index?${query}`
    })
}



// 监听页面显示
onMounted(() => {
    fetchFavorites()
})
</script>

<style>
.container {
    background: #f5f5f5;
    min-height: 100vh;
}

/* 选项卡样式 */
.tabs {
    display: flex;
    background: #ffffff;
    padding: 20rpx;
    position: sticky;
    top: 0;
    z-index: 1;
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
}

.tab-item.active {
    color: #35495e;
    font-weight: bold;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 40rpx;
    height: 4rpx;
    background: #35495e;
    border-radius: 2rpx;
}

/* 内容区域样式 */
.content-section {
    height: calc(100vh - 120rpx);
    padding: 20rpx;
}

.content {
    margin-top: 80rpx;
}

/* 营地卡片样式 */
.camp-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.camp-item {
    background: #ffffff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    position: relative;
}

.camp-image {
    width: 100%;
    height: 300rpx;
}

.camp-info {
    padding: 20rpx;
}

.camp-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
}

.camp-meta {
    font-size: 24rpx;
    color: #999;
}

/* 攻略卡片样式 */
.guide-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.guide-item {
    background: #ffffff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    position: relative;
}

.guide-image {
    width: 100%;
    height: 300rpx;
}

.guide-info {
    padding: 20rpx;
}

.guide-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
}

.guide-desc {
    font-size: 26rpx;
    color: #666;
}

/* 空状态样式 */
.empty-state {
    text-align: center;
    padding: 100rpx 0;
    color: #999;
    font-size: 28rpx;
}

/* 删除按钮样式 */
.delete-btn {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 44rpx;
    height: 44rpx;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 22rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    z-index: 1;
}

.delete-btn:active {
    background: rgba(0, 0, 0, 0.7);
}

.camp-content,
.guide-content {
    width: 100%;
    height: 100%;
}
</style>